package com.lanhai.zhonglai.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lanhai.zhonglai.beans.AgvDataBean;
import com.lanhai.zhonglai.dispatch.DispatchAgv;
import com.lanhai.zhonglai.interfaces.IAgv;


/**
 *  小车的消息获取
 * @author virus408
 *
 */
@Component
public class AgvListener {
	@Autowired
	DispatchAgv dAgv;

	@Autowired
	IAgv iagv;


	private boolean running;
	private Thread th;

	public void Start(int port) {
		running=true;
		System.out.println("启动AGV侦听线程");
		th=new Thread() {
			@Override
			public void run() {
				try{
					DatagramSocket	ds = new DatagramSocket(port);
					while(running){
						byte buf[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(buf, buf.length);
						ds.receive(dp);


						if(buf[0]==-95) {
							//只处理小车的
							AgvDataBean bb=iagv.analyseData(buf);
							if(bb!=null &&(bb.getAgvId()>0) ) {
								dAgv.saveAgvState(bb,dp.getAddress().getHostAddress());//保存agv状态到redis, 保存agv变化状态到数据库
								dAgv.resolve(bb);
							}

						}
					}
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}

		};
		th.start();
	}


	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null;
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
